<?php
header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置
$dbConfig = include('db_config.php');

// 获取前端传过来的视频 ID
$video_id = $_POST['video_id'] ?? '';

// 检查视频 ID 是否为空
if (empty($video_id)) {
    $result = [
        'status' => 'error',
        'message' => '视频 ID 不能为空'
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
    exit;
}

// 创建数据库连接
try {
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 查询视频信息
    $selectVideoStmt = $pdo->prepare("SELECT * FROM mi_videos WHERE id = :video_id");
    $selectVideoStmt->bindParam(':video_id', $video_id);
    $selectVideoStmt->execute();
    $video = $selectVideoStmt->fetch(PDO::FETCH_ASSOC);

    if (!$video) {
        $result = [
            'status' => 'error',
            'message' => '视频不存在'
        ];
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
        exit;
    }

    // 获取视频文件路径和封面文件路径
    $videoFilePath = $video['视频链接'];
    $videoCoverPath = $video['视频封面'];

    // 删除视频文件和封面文件
    if (file_exists($videoFilePath)) {
        unlink($videoFilePath);
    }

    if (file_exists($videoCoverPath)) {
        unlink($videoCoverPath);
    }

    // 删除数据库中的视频记录
    $deleteVideoStmt = $pdo->prepare("DELETE FROM mi_videos WHERE id = :video_id");
    $deleteVideoStmt->bindParam(':video_id', $video_id);
    $deleteVideoStmt->execute();

    // 检查删除是否成功
    if ($deleteVideoStmt->rowCount() > 0) {
        $result = [
            'status' => 'success',
            'message' => '视频删除成功'
        ];
    } else {
        $result = [
            'status' => 'error',
            'message' => '视频删除失败'
        ];
    }

    echo json_encode($result, JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    // 数据库操作失败
    $result = [
        'status' => 'error',
        'message' => '数据库操作失败：' . $e->getMessage()
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    // 其他异常
    $result = [
        'status' => 'error',
        'message' => '操作失败：' . $e->getMessage()
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
}
?>
